import { BaseGraph, IBaseProps } from './graph/base'
import { Group } from './graph/group'

export interface IBoardProps extends IBaseProps {
  create?: boolean
}

export default class Board extends Group {
  public children: Array<BaseGraph> = []
  public canvas: HTMLCanvasElement = document.createElement('canvas')
  public ctx: CanvasRenderingContext2D = this.canvas.getContext('2d')
  private devicePixelRatio = 1
  public element: HTMLElement = null
  public height: number = 0
  public width: number = 0
  public centerX: number = 0
  public centerY: number = 0
  private animated: boolean = false
  private create: boolean = false
  constructor(element: HTMLElement, props?: IBoardProps) {
    super(props)
    this.element = element
    this.create = props?.create
    this.canvas.width = this.canvas.height = 0
    // 增加child
    if (this.create) {
      this.element.style.overflow = 'hidden'
      this.element.innerHTML = ''
      this.element.appendChild(this.canvas)
    }
    this.devicePixelRatio = window.devicePixelRatio || 1
    // 高清适配
    this.matrix.matrix = this.matrix.scaleTo(this.devicePixelRatio, this.devicePixelRatio)
    this.resize()
  }
  public render() {
    this.draw(this.ctx)
  }
  public animate() {
    if (!this.animated) return
    this.render()
    window.requestAnimationFrame(() => this.animate())
  }
  public resize() {
    this.height = this.element.clientHeight
    this.width = this.element.clientWidth
    this.centerX = this.width / 2
    this.centerY = this.height / 2
    this.canvas.style.width = this.width + 'px'
    this.canvas.style.height = this.height + 'px'
    this.canvas.width = this.width * this.devicePixelRatio
    this.canvas.height = this.height * this.devicePixelRatio
    if (!this.animated) this.render()
  }
  public draw(ctx: CanvasRenderingContext2D): void {
    // 清除因为变换清除不掉的像素
    ctx.resetTransform()
    // 清除画布
    ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
    // 变换矩阵
    // @ts-ignore
    ctx.setTransform(...this.matrix.matrix)
    // 绘制模型
    for (let i = 0; i < this.children.length; i++) {
      this.children[i].draw(ctx)
    }
  }
  public clearRect(x: number, y: number, width: number, height: number) {
    this.ctx.clearRect(x, y, width, height)
  }
  public getUrl() {
    this.render()
    return this.canvas.toDataURL('image/png')
  }
  public getStyle() {
    return `url(${this.getUrl()}) 0 0/100% 100%`
  }
  public setPath() {}
  public drawPath(ctx: CanvasRenderingContext2D): void {}
}
